package com.qiniu.util;

import java.io.File;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @ClassName QUploadUtil
 * @date 2017年11月14日 下午2:22:15
 */
public class QUploadUtil {

    private static String ACCESS_KEY = null;
    private static String SECRET_KEY = null;
    private static String BUCKET_NAME = null;
    public static String BUCKET_HOST_NAME = null;
    private static long expireSeconds = 12 * 3600; // token过期时间

    private static UploadManager uploadManager = null;
    private static String upToken = null;

    static {
	initConfig();
	Configuration cfg = new Configuration(Zone.autoZone());
	uploadManager = new UploadManager(cfg);
	Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	upToken = auth.uploadToken(BUCKET_NAME, null, expireSeconds, null);
    }

    public static String uploadFile(File file) {
	try {
	    // 默认以文件文件名
	    Response response = uploadManager.put(file, file.getName(), upToken, null, null, true);
	    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
	    return putRet.hash;
	} catch (QiniuException e) {
	    e.printStackTrace();
	}
	return null;
    }

    private static void initConfig() {
	Properties prop = new Properties();
	try {
	    InputStream in = ClassLoader.getSystemResourceAsStream("config.properties");
	    if(in == null){
		in = ClassLoader.getSystemResourceAsStream("resources/config.properties");
	    }
	    prop.load(in);
	    Iterator<String> it = prop.stringPropertyNames().iterator();
	    while (it.hasNext()) {
		String key = it.next();
		switch (key) {
		case "access":
		    ACCESS_KEY = prop.getProperty(key).trim();
		    break;
		case "secret":
		    SECRET_KEY = prop.getProperty(key).trim();
		    break;
		case "bucket":
		    BUCKET_NAME = prop.getProperty(key).trim();
		    break;
		case "host_name":
		    BUCKET_HOST_NAME = prop.getProperty(key).trim();
		    break;
		default:
		    break;
		}
	    }
	    in.close();
	} catch (Exception e) {
	    System.out.println("init config error");
	    e.printStackTrace();
	}
    }

}
